package yhao.demo.web.firstWeb.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import yhao.demo.service.login.apilist.LoginCacheKey;
import yhao.demo.service.login.apilist.ReturnCodeEnum;
import yhao.demo.service.login.apilist.model.LoginPersonModel;
import yhao.demo.web.firstWeb.config.ApiSwaggerTags;
import yhao.demo.web.firstWeb.config.AuthorityAnnotation;
import yhao.demo.web.firstWeb.config.AuthorityAnnotationEnums;
import yhao.demo.web.firstWeb.constants.WebDemoConstants;
import yhao.demo.web.firstWeb.remote.LoginRemote;
import yhao.infra.apilist.validate.IdForm;
import yhao.infra.apilist.validate.LoginForm;
import yhao.infra.common.cache.YhaoCache;

import javax.annotation.Resource;


@Lazy
@RestController
@RequestMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
@Api(value = ApiSwaggerTags.DEMO_TAG, description = "first")
public class LoginController extends WebBaseController {
    @Resource
    private YhaoCache yhaoCache;
    @Autowired
    private LoginRemote loginRemote;

    @AuthorityAnnotation(AuthorityAnnotationEnums.ADMIN)
    @PostMapping(value = "/loginIn")
    @ApiOperation(value = "登录接口")
    @ApiResponses({
            @ApiResponse(message = "登录接口传参", code = 200, response = IdForm.class)
    })
    public String loginIn(@RequestBody LoginForm form) {
        //错误登录次数校验
        String key = form.getUserName();
        long loginTime = yhaoCache.incr(LoginCacheKey.CACHE_LOGIN_LIMIT,key);
        if(loginTime>5){    //登录次数过多
            return wrong(ReturnCodeEnum.FOA_LOGIN_0001);
        }
        yhaoCache.expire(LoginCacheKey.CACHE_LOGIN_LIMIT,key,2*60);

        LoginPersonModel loginPerson = loginRemote.authenticatePerson(form);
        yhaoCache.remove(LoginCacheKey.CACHE_LOGIN_LIMIT,key);
        getRequest().getSession().setAttribute(WebDemoConstants.CURRENT_LOGIN_PERSON, loginPerson);
        return successInfo(loginPerson);
    }

    @GetMapping(value = "logOut")
    @ApiOperation(value = "用户退出")
    @ApiResponses({
            @ApiResponse(message = "用户退出,无结果返回", code = 200, response = String.class)
    })
    public String logOut() {
        getRequest().getSession().removeAttribute(WebDemoConstants.CURRENT_LOGIN_PERSON);
        return successInfo();
    }
}
